import wx
import ftplib
import os
import socket

FTP_TRANSFER_STATUS_DONE = 1
FTP_TRANSFER_STATUS_NOT_DONE = -1

class FTPTransfer(wx.Dialog):
    def __init__(self, listOfFile):
        wx.Dialog.__init__(self, None, -1, 'FTP Transfer', size=(300, 165))
        self.hostLabel = wx.StaticText(self, -1, "Host:",  pos=(15, 17))
        self.hostText = wx.TextCtrl(self, -1, "", size=(175, -1),  pos=(100, 15))  
       
        self.usernameLabel = wx.StaticText(self, -1, "Username:",  pos=(15, 43))
        self.usernameText = wx.TextCtrl(self, -1, "", size=(175, -1),  pos=(100, 41))
        
        self.pwdLabel = wx.StaticText(self, -1, "Password:",  pos=(15, 69))
        self.pwdText = wx.TextCtrl(self, -1, "", size=(175, -1),style=wx.TE_PASSWORD,  pos=(100, 67))
        
        okButton = wx.Button(self, wx.ID_OK, "OK", pos=(85, 100))
        okButton.SetDefault()
        okButton.Bind(wx.EVT_BUTTON, self.initialiseTransfer)
        
        cancelButton = wx.Button(self, wx.ID_CANCEL, "Cancel",pos=(185, 100))

        self.listOfFile = listOfFile
        

    def initialiseTransfer(self, event15):
        self.password = self.pwdText.GetValue()
        self.username = self.usernameText.GetValue()
        self.host = self.hostText.GetValue()
        self.dir = os.getcwd()
        status = self.login()
        if status == FTP_TRANSFER_STATUS_DONE:
            self.Destroy()
        
        # login to FTP
    def login (self):
        if self.host and self.password and self.username:
            try:
                ftp = ftplib.FTP(str(self.host))
                ftp.login(self.username, self.password)
                ftp.cwd("/home/" + self.username)
                os.chdir(self.dir)
                for fileItem in self.listOfFile:
                    myfile = open(fileItem, 'r')
                    ftp.storlines('STOR ' + fileItem, myfile)
                    myfile.close()
                    print fileItem, "transferred"
                return FTP_TRANSFER_STATUS_DONE
            except socket.gaierror:
                print "Input error"
                self.clearField()
                return FTP_TRANSFER_STATUS_NOT_DONE
        else:
            print "Please enter fields."
            return FTP_TRANSFER_STATUS_NOT_DONE

    def clearField(self):
        self.pwdText.SetValue("")
        self.usernameText.SetValue("")
        self.hostText.SetValue("")
        self.usernameText.SetFocus()
        
        
        
        